import axios, { type Method, AxiosRequestConfig, AxiosResponse } from "axios";
// import { ElMessage } from 'element-plus'
import router from "@/router";

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 50000,
});

// 请求拦截器 AxiosRequestConfig 请求参数类型
service.interceptors.request.use((config: AxiosRequestConfig | any) => config);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const data = response.data
    if (data.code === 0) {
      if (data.msg === 'NOTLOGIN') {
        localStorage.clear()
        router.push('/login')
      }
      return Promise.reject(data.msg)
    }
    return data;
  },
  (error) => {
    return Promise.reject(error);
  }
);

type Data<T> = {
  code: number;
  msg: string;
  data: T;
};

const request = <T>(
  url: string,
  method: Method,
  submitData?: object | T,
  config?: AxiosRequestConfig
) => {
  return service.request<T, Data<T>>({
		url,
		method,
		[method.toLowerCase() === 'get' ? 'params' : 'data']: submitData,
		...config
	})
};

export default request;